package com.newcoder.community.controller;

import com.newcoder.community.entity.Page;
import com.newcoder.community.pojo.Message;
import com.newcoder.community.pojo.User;
import com.newcoder.community.serverce.MessageService;
import com.newcoder.community.serverce.UserService;
import com.newcoder.community.utill.CommunityUtill;
import com.newcoder.community.utill.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
public class MessageController {
    @Autowired
    private MessageService messageService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;

    @GetMapping("/letter/list")
    public String getLetterList(Page page, Model model) {

        User user = hostHolder.getUser();
        page.setLimit(5);
        page.setRows(messageService.selectConversationCount(user.getId()));
        page.setPath("/letter/list");
        List<Message> conversationList = messageService.selectConversations(user.getId(), page.getOffset(), page.getLimit());
        List<Map<String, Object>> conversations = new ArrayList<>();
        for (Message message : conversationList) {
            Map<String, Object> map = new HashMap<>();
            map.put("conversation", message);
            map.put("letterCount", messageService.selectLetterCount(message.getConversationId()));
            map.put("unreadCount", messageService.selectLettersUnreadCount(user.getId(), message.getConversationId()));
            int targetId = user.getId() == message.getToId() ? message.getFromId() : message.getToId();
            map.put("target", userService.selectById(targetId));
            conversations.add(map);

        }
        model.addAttribute("conversations", conversations);
        model.addAttribute("lettersUnreadCount", messageService.selectLettersUnreadCount(user.getId(), null));
        return "/site/letter";
    }

    @GetMapping("/letter/detail/{conversationId}")
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page page, Model model) {
        User contentUser = hostHolder.getUser();
        page.setRows(messageService.selectLetterCount(conversationId));
        page.setLimit(5);
        page.setPath("/letter/detail/" + conversationId);
        List<Message> letterList = messageService.selectLetters(conversationId, page.getOffset(), page.getLimit());
        List<Map<String, Object>> letters = new ArrayList<>();
        for (Message message : letterList) {
            Map<String, Object> map = new HashMap<>();
            User user = userService.selectById(message.getFromId());
            map.put("fromUser", user);
            map.put("letter", message);
            letters.add(map);
           if(contentUser.getId()!=user.getId()){
               messageService.updateStatus(message.getId());
           }

        }
        model.addAttribute("letters", letters);
        model.addAttribute("target",getLetterTarget(conversationId));
        System.out.println("修改2");
        return "/site/letter-detail";
    }

    @PostMapping("/letter/send")
    @ResponseBody
    public String sendLetter(String toName,String content){

        User toUser = userService.selectByName(toName);
        if(toUser==null){
            return CommunityUtill.getJson(1,"目标用户不存在");
        }
        User fromUser = hostHolder.getUser();
        Message message = new Message();
        message.setContent(content);
        String conversationId = fromUser.getId()>toUser.getId()?toUser.getId()+"_"+fromUser.getId():fromUser.getId()+"_"+toUser.getId();
        message.setConversationId(conversationId);
        message.setToId(toUser.getId());
        message.setFromId(fromUser.getId());
        message.setCreateTime(new Date());
        messageService.insertMessage(message);
        return CommunityUtill.getJson(0);
    }

    public User getLetterTarget(String conversationId) {
        User user = hostHolder.getUser();
        String[] id = conversationId.split("_");
        int id1 = Integer.parseInt(id[0]);
        int id2 = Integer.parseInt(id[1]);
        int targetId = user.getId() == id1 ? id2 : id1;
        return userService.selectById(targetId);
    }
}
